package com.dwj.auto.comment.common.wechat.handler;

import com.dwj.auto.comment.common.response.Response;
import com.dwj.auto.comment.common.utils.CodeUtil;
import com.dwj.auto.comment.dao.entity.SubscribeUser;
import com.dwj.auto.comment.dao.entity.User;
import com.dwj.auto.comment.model.form.UserForm;
import com.dwj.auto.comment.model.wechat.WxMessage;
import com.dwj.auto.comment.service.ISubscribeUserService;
import com.dwj.auto.comment.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName RegisterListener
 * @Description 注册监听者
 * @Author dwjian
 * @Date 2020/12/26 19:16
 */
@Slf4j
@Component
public class RegisterHandler extends WxTextMessageHandler implements WxMessageHandler {

    @Resource
    private IUserService userService;
    @Resource
    private ISubscribeUserService subscribeUserService;

    @Override
    public String dealMessage(WxMessage message) {
        SubscribeUser localSubscribeUser = subscribeUserService.lambdaQuery().eq(SubscribeUser::getOpenId, message.getOpenId()).eq(SubscribeUser::getIsDel, 0).one();
        if (localSubscribeUser != null && localSubscribeUser.getIsDistribution() == 1) {
            User user = userService.lambdaQuery().eq(User::getId, localSubscribeUser.getUserId()).eq(User::getIsDel, 0).one();
            return "您已经注册过（账号：" + user.getUsername() + "）\n如忘记密码请发送“重置密码：新密码”。\n例如“重置密码：123456”\n注意：新密码必须由六位数字或字母组成。";
        }
        //注册账号
        String username = CodeUtil.createUsername();
        String password = CodeUtil.createPassword(8);
        UserForm form = new UserForm();
        form.setUsername(username);
        form.setPassword(password);
        form.setRePassword(password);
        form.setRoleIds("059ea109c7224c11920993f8c6e07f6i");
        Response<String> response = userService.edit(form);
        if (response.isOK()) {
            String userId = response.getData();
            subscribeUserService.lambdaUpdate()
                    .eq(SubscribeUser::getOpenId, message.getOpenId())
                    .set(SubscribeUser::getIsDistribution, 1)
                    .set(SubscribeUser::getUserId, userId).update();
            if (localSubscribeUser == null) {
                //老用户记录关注
                SubscribeUser oldFansUser = new SubscribeUser();
                oldFansUser.setId(CodeUtil.uuid());
                oldFansUser.setOpenId(message.getOpenId());
                oldFansUser.setStatus(1);
                oldFansUser.setIsDistribution(1);
                oldFansUser.setUserId(userId);
                subscribeUserService.getBaseMapper().insert(oldFansUser);
                log.info("公众号历史粉丝注册账号");
            }
            return "恭喜您注册成功！\n您的账号：" + username + "\n您的密码：" + password + "\n请用电脑打开网站https://auto-comment.top进行登录。";
        }
        return "注册失败，请联系QQ315200140反馈问题。";
    }
}
